package org.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: guochuang
 * @date: 2025-03-13 17:11
 **/
public class JdbcUtil {


    private static Map<String, List<ColumnMetadata>> columnMetadataMap = new HashMap<>();

    public static List<ColumnMetadata> getColumns(String database, String table) {
        String tableSchema = String.format("%s.%s", database, table);
        List<ColumnMetadata> columns = columnMetadataMap.get(tableSchema);
        try {
            if (columns == null) {
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true",
                        "root", "guochuang123");
                //查询表中列信息
                PreparedStatement statement = connection.prepareStatement(
                        "select COLUMN_NAME, DATA_TYPE, CHARACTER_SET_NAME from INFORMATION_SCHEMA.COLUMNS " +
                                "where TABLE_SCHEMA=? and TABLE_NAME=? order by ORDINAL_POSITION asc;");
                statement.setString(1, database);
                statement.setString(2, table);
                ResultSet resultSet = statement.executeQuery();
                List<ColumnMetadata> columnMetadataList = new ArrayList<>();
                while (resultSet.next()) {
                    ColumnMetadata column = new ColumnMetadata();
                    column.setColumnName(resultSet.getString("COLUMN_NAME"));
                    column.setDataType(resultSet.getString("DATA_TYPE"));
                    column.setCharacterSetName(resultSet.getString("CHARACTER_SET_NAME"));
                    columnMetadataList.add(column);
                }
                columns = columnMetadataList;
                columnMetadataMap.put(tableSchema, columnMetadataList);
            }
            return columns;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return columns;
    }
}
